package chzhenjia.learn.androidcode.three;

import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import chzhenjia.learn.androidcode.ApplicationTest;

/**
 * 作者:陈圳佳
 * 日期:2015/8/2
 */
public class DatabaseTest extends ApplicationTest {

    private SQLiteDatabase db;


    @Override
    public void setUp() throws Exception {
        DBHelper dbHelper = new DBHelper(getContext());
        db = dbHelper.getWritableDatabase();
        System.out.println("setUp run.............");
    }

    @Override
    public void tearDown() throws Exception {
        System.out.println("tearDown run....");
        db.close();
    }

    public void testCreateTable() {
        System.out.printf("testCreateTable run...");
    }

    /**
     * 插入数据
     *
     * @throws Exception
     */
    public void testInsert() throws Exception {
        ContentValues values = new ContentValues();
        values.put("name", "小明");
        values.put("salary", 2433d);
        db.insert("person", null, values);
    }

    /**
     * 删除数据
     *
     * @throws Exception
     */
    public void testDelete() throws Exception {
        db.delete("person", "id=?", new String[]{"1"});
    }

    /**
     * 更新数据
     *
     * @throws Exception
     */
    public void testUpdate() throws Exception {
        ContentValues values = new ContentValues();
        values.put("salary", 4999);
        db.update("person", values, "_id=?", new String[]{"1"});

    }

    /**
     * 查询数据
     *
     * @throws Exception
     */
    public void testSelect() throws Exception {
        Cursor cursor = db.query("person", null, null, null, null, null, null);
        while (cursor.moveToNext()) {
            System.out.println("id=" + cursor.getInt(cursor.getColumnIndex("_id")));
            System.out.println("name=" + cursor.getString(cursor.getColumnIndex("name")));
            System.out.println("salary=" + cursor.getDouble(cursor.getColumnIndex("salary")));
        }
        cursor.close();
    }

    /**
     * SQLite 的事物
     *
     * @throws Exception
     */
    public void testTransaction() throws Exception {
        db.beginTransaction();
        try {
            Cursor cursor = db.query("person", new String[]{"salary"}, "_id=?", new String[]{"1"}, null, null, null, null);
            double salary = 0d;
            if (cursor.moveToNext()) {
                salary = cursor.getDouble(cursor.getColumnIndex("salary"));
            }
            cursor.close();
            double a = 0 / salary;
            ContentValues values = new ContentValues();
            values.put("salary", salary -= 1111);
            db.update("person", values, "id=?", new String[]{"1"});
            db.setTransactionSuccessful();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            db.endTransaction();
        }

    }
}
